<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>canvas连线</title>
</head>
<style>
	*{
		margin:0px;
		padding:0px;
	}
	#goudan{
		display:block;
		background:#000;
	}
</style>
<body>
	<canvas id="goudan"width=100 height=100>
		次浏览器不支持Canvas
	</canvas>
</body>
<script>
	var cas=document.getElementById("goudan");
	var cxt=cas.getContext("2d");
	//如何画一条线
	var w = cas.width=window.innerWidth;
	var h = cas.height=window.innerHeight;
	var num = 300;
	var data = [];//定义初始坐标
	var move = {};//定义一个json存储鼠标坐标
	for(var i=0;i<num;i++){//随机生成点
		var x=Math.random()*w;
		var y=Math.random()*h;
		Cricle(x,y);
	};
	for(var i=0;i<num;i++){//将初始坐标添加在数组data中
		data[i]=[];
		data[i].x=Math.random()*w;
		data[i].y=Math.random()*h;
		data[i].cx=Math.random()*4-2;
		data[i].cy=Math.random()*4-2;
		data[i].isLine=false;
		Cricle(data[i].x,data[i].y);
	};
	+function draw()
	{
		cxt.clearRect(0,0,w,h);
		window.requestAnimationFrame(draw);
		for(var i=0;i<num;i++)
		{
			data[i].x+=data[i].cx;
			if(data[i].x>w ||data[i].x<0)data[i].cx=-data[i].cx;
			data[i].y+=data[i].cy;
			if(data[i].y>h ||data[i].y<0)data[i].cy=-data[i].cy;
			Cricle(data[i].x,data[i].y);
			for(var j=i+1;j<num;j++)
			{
				if((data[i].x-data[j].x)*(data[i].x-data[j].x)+(data[i].y-data[j].y)*(data[i].y-data[j].y)<=50*50)
				{
					Line(data[i].x,data[i].y,data[j].x,data[j].y)
				};
				if(move.x)
				{
					var l=(data[i].x-move.x)*(data[i].x-move.x)+(data[i].y-move.y)*(data[i].y-move.y);
					if(data[i].isLine)
					{
						if(l>100*100)
						{
							data[i].cx=-data[i].cx;
							data[i].cy=-data[i].cy;
						}
					}else
					{
						if(l<=100*100)
						{
							data[i].isLine=true;
						};
					};
				};

			};
		};
	}();
	document.onmousemove=function(e){//绑定鼠标移入事件
		move.x = e.pageX;
		move.y = e.pageY;
		for(var i=0;i<num;i++)data[i].isLine=false;
	}
	document.onmouseleave=function(){//鼠标移出事件
		move={};
		for(var i=0;i<num;i++)data[i].isLine=false;
	}
	//划圆
	function Cricle(x,y)
	{
		cxt.fillStyle="pink";
		cxt.beginPath();
		cxt.arc(x,y,1,0.3,2*Math.PI,true);
		cxt.closePath();
		cxt.fill();
	}
	//画线
	function Line(x1,y1,x2,y2)
	{
		var lin=cxt.createLinearGradient(x1,y1,x2,y2);
			lin.addColorStop(0,"#9900ff");
			lin.addColorStop(1,"#00ffff");
		cxt.strokeStyle=lin;
		cxt.moveTo(x1,y1);
		cxt.lineTo(x2,y2);
		cxt.stroke();
	}
</script>
</html>